package cn.wfu.rlrjds.common.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.wfu.rlrjds.web.admin.dao.IAdminDao;
import cn.wfu.rlrjds.web.admin.domain.Admin;

public class LoginRealm extends AuthorizingRealm {

	@Autowired
	private IAdminDao adminDao;

	/**
	 * 授权授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String userName = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(adminDao.getRoles(userName));
		authorizationInfo.setStringPermissions(adminDao
				.getPermissions(userName));
		return authorizationInfo;
	}

	/**
	 * 登陆验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username = (String) token.getPrincipal();
		Admin admin = adminDao.findBy("findByUsername", username);
		if (admin != null) {
			AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
					admin.getUsername(), admin.getPassword(), getName());
			return authenticationInfo;
		} else {
			return null;
		}
	}
}
